package com.yupi.yuapiinterface.service.impl;

import com.jair.apicommon.service.InterfaceInvokeService;
import com.jair.apicommon.model.dto.InterfaceRequest;
import com.jair.apicommon.model.InterfaceResponse;
import com.yupi.yuapiinterface.model.User;
import com.yupi.yuapiinterface.service.UserService;
import com.yupi.yuapiclientsdk.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@DubboService(version = "1.0.0", group = "dev")
public class InterfaceInvokeServiceImpl implements InterfaceInvokeService {

    @Resource
    private UserService userService;

    @Override
    public InterfaceResponse invokeInterface(String name, String method, String params) {
        log.info("Dubbo调用接口: name={}, method={}, params={}", name, method, params);

        try {
            String result;
            if ("GET".equalsIgnoreCase(method)) {
                result = "GET 你的名字是" + name + " (Dubbo调用)";
            } else if ("POST".equalsIgnoreCase(method)) {
                result = "POST 你的名字是" + name + " (Dubbo调用)";
            } else {
                return InterfaceResponse.error("不支持的请求方法: " + method);
            }

            return InterfaceResponse.success(result);
        } catch (Exception e) {
            log.error("接口调用失败", e);
            return InterfaceResponse.error("接口调用失败: " + e.getMessage());
        }
    }

    @Override
    public InterfaceResponse invokeInterfaceWithAuth(String name, String method, String params,
                                                     String accessKey, String secretKey) {
        log.info("Dubbo带认证调用接口: name={}, method={}, params={}, accessKey={}",
                name, method, params, accessKey);

        try {
            // 1. 用户认证
            if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey)) {
                return InterfaceResponse.error("accessKey或secretKey为空");
            }

            User user = userService.getByAccessKey(accessKey);
            if (user == null) {
                return InterfaceResponse.error("用户不存在");
            }

            // 2. 签名验证（简化版）
            String body = params;
            String sign = SignUtils.genSign(body, secretKey);
            log.info("签名验证 - body: {}, secretKey: {}, sign: {}", body, secretKey, sign);

            // 3. 执行接口调用
            String result;
            if ("GET".equalsIgnoreCase(method)) {
                result = "GET 你的名字是" + name + " (Dubbo认证调用)";
            } else if ("POST".equalsIgnoreCase(method)) {
                result = "POST 你的名字是" + name + " (Dubbo认证调用)";
            } else {
                return InterfaceResponse.error("不支持的请求方法: " + method);
            }

            // 4. 记录调用日志
            log.info("接口调用成功 - 用户: {}, 接口: {}, 结果: {}",
                    user.getUserAccount(), name, result);

            return InterfaceResponse.success(result);

        } catch (Exception e) {
            log.error("带认证接口调用失败", e);
            return InterfaceResponse.error("接口调用失败: " + e.getMessage());
        }
    }

    @Override
    public List<InterfaceResponse> batchInvoke(List<InterfaceRequest> requests) {
        return requests.stream()
                .map(req -> invokeInterface(req.getName(), req.getMethod(), req.getParams()))
                .collect(Collectors.toList());
    }

    @Override
    public Long getInvokeCount(String interfaceName) {
        log.info("获取接口调用次数: {}", interfaceName);
        return 100L; // 示例返回值
    }

    @Override
    public String healthCheck() {
        return "InterfaceInvokeService is healthy (Dubbo)";
    }

    @Override
    public String getInvokeMethod() {
        return "Dubbo RPC";
    }
}